//①Homework2.java
package edu.neuq.homework;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
//先做好界面，再进行读写操作
public class Homework2 extends JFrame{
	
	public JButton jbsave;
	public JButton jbload;
	
	public JTextField jtfname;
	public JTextField jtfage;
	public JTextField jtfnation;
		
	public Homework2(){
		jbsave = new JButton("保存");
		jbload = new JButton("读取");
		
	    jbsave.addActionListener(new ActionListener(){//写：保存

		@Override
		public void actionPerformed(ActionEvent arg0) {
			String name=jtfname.getText();
			String age=jtfage.getText();
			String nation=jtfnation.getText();
			Student stu=new Student();
			stu.age=age;
			stu.name=name;
			stu.nation=nation;
			jbsave.setForeground(Color.BLUE);
			
			FileOutputStream fos;
			try{
			fos=new FileOutputStream("hero.tmp");
			ObjectOutputStream oos= new ObjectOutputStream(fos);
			oos.writeObject(stu);
			fos.close();
			oos.close();
		    }catch (Exception e){
			e.printStackTrace();}
	  }
  });
	
	    jbload.addActionListener(new ActionListener(){//读：读取

		@Override
		public void actionPerformed(ActionEvent e) {			
			try{
			FileInputStream fis=new FileInputStream("hero.tmp");
			ObjectInputStream ois=new ObjectInputStream(fis);
			Student stu=(Student) ois.readObject();
			jtfname.setText(stu.name);
			jtfage.setText(stu.age);
			jtfnation.setText(stu.nation);
			}catch (Exception e1) {
				e1.printStackTrace();}
	  }
  });
	
	jtfname=new JTextField();
	jtfage=new JTextField();
	jtfnation=new JTextField();
	this.setLayout(new GridLayout(4,2));
	
	Font f=new Font("宋体",Font.BOLD,28);
	jbsave.setFont(f);
	jbload.setFont(f);
	jtfname.setFont(f);
	jtfage.setFont(f);
	jtfnation.setFont(f);

	JLabel ok1 = new JLabel("姓名",JLabel.CENTER);
	ok1.setFont(f);
	JLabel ok2 = new JLabel("年龄",JLabel.CENTER);
	ok2.setFont(f);
	JLabel ok3 = new JLabel("国籍",JLabel.CENTER);
	ok3.setFont(f);
	
	this.add(ok1,BorderLayout.CENTER);
	this.add(jtfname);
	this.add(ok2,BorderLayout.CENTER);
	this.add(jtfage);
	this.add(ok3,BorderLayout.CENTER);
	this.add(jtfnation);
	
	this.add(jbsave);
	this.add(jbload);
	
	this.setSize(800,600);
	this.setTitle("Student");
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
	this.setVisible(true);
	}
	public static void main(String[] args) {
		new Homework2();
	}
}


//②Student.java
package edu.neuq.homework;

import java.io.Serializable;

public class Student implements Serializable{
	String name;
	String age;
	String nation;
}

